﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.Security;

namespace GoodStuff.Web
{
    /// <summary>
    /// When this module is registered in the web.config, it will automatically redirect the client
    /// to the login page when the session has timed out.
    /// </summary>
    /// <remarks>
    /// It requires no configuration, but FormsAuthentication must be used to detect the login page.
    /// </remarks>
    public class SessionTimeoutModule : IHttpModule
    {
        public void Dispose()
        {            
        }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)
            {
                page.PreRender += new EventHandler(page_PreRender);                
            }
        }

        void page_PreRender(object sender, EventArgs e)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)           //zou niet mogen gebeuren, maar toch even checken.
            {
                page.PreRender += new EventHandler(page_PreRender);

                string loginUrl = FormsAuthentication.LoginUrl;
                TimeSpan timeOut = TimeSpan.FromMinutes(page.Session.Timeout);

                //only redirect when this page is not the login page.
                if (HttpContext.Current.Request.Url.AbsolutePath != loginUrl)
                {
                    ScriptManager.RegisterStartupScript(
                        page,
                        typeof(SessionTimeoutModule),
                        "TimeoutRedirector",
                        string.Format(@"window.setTimeout(""window.location.href='{0}'"",{1});", loginUrl, timeOut.TotalMilliseconds)
                       , true);
                }
            }
        }
    }
}
